# -*- coding:utf-8 -*-
# -------------------------------------------------------------------------------
# Description:  
# Reference:
# Author: 安智军
# Date:   2021/12/14
# -------------------------------------------------------------------------------
import logging
import os
import time
import traceback
from functools import wraps
from config.config import basepath

log_path = basepath+"/Outputs/logs/"
print(log_path)
if not os.path.exists(log_path): # 如果log文件夹地址不存在则创建地址
    os.mkdir(log_path)


class Logger():

    def __init__(self):
        # 创建日志路径及时间
        #  #time strftime() 函数接收以时间元组，并返回以可读字符串表示的当地时间
        # self.logname = os.path.join(log_path,"{}.log".format(time.strftime()))
        self.logname = log_path+"{}.log".format(time.strftime("%Y%m%d"))
        # 创建一个logger日志对象
        self.logger = logging.getLogger("log")
        # 设置日志格式的默认级别
        self.logger.setLevel(logging.DEBUG)
        # 创建日志格式对象
        self.formater = logging.Formatter('[%(asctime)s][%(filename)s %(lineno)d][%(levelname)s]: %(message)s')
        # 创建FileHandler对象 mode = 'a' a=append=追加，即 给文件保存写入内容，不是覆盖之前已有文件中内容，而是放在最后，追加到最后。
        self.filelogger = logging.FileHandler(self.logname,mode="a",encoding="UTF-8")
        # 创建streamHandler
        self.console = logging.StreamHandler()
        # FileHandler对象自定义日志级别
        self.console.setLevel(logging.DEBUG)
        self.filelogger.setLevel(logging.DEBUG)
        # 设置两个地方格式
        self.filelogger.setFormatter(self.formater)
        self.console.setFormatter(self.formater)

        # logger日志对象加载FileHandler对象
        self.logger.addHandler(self.filelogger)
        # logger日志对象加载streamHandler对象
        self.logger.addHandler(self.console)


Logger = Logger().logger


def decorate_log(func):
    @wraps(func) # 不改变使用装饰器原有函数的结构(如name, doc)

    def log(*args,**kwargs):
        logging.info(f"---------开始执行{func.__name__}用例------")
        try:
            func(*args,**kwargs)
        except Exception as e:
            Logger.error(f'-----{func.__name__}用例执行失败，失败原因：{e}-----')
            Logger.error(f"{func.__name__} 用例 is error,here are details:{traceback.format_exc()}")
            raise e
        else:
            Logger.info(f'______{func.__name__}执行成功')
    return log


@decorate_log
def test_num():
    assert 2==3


if __name__ == '__main__':
    test_num()

